package com.design.pattern.controller;

import com.design.pattern.observer.event.UserService;
import com.design.pattern.pipel.ModelService;
import com.design.pattern.strategy.StrategyPatternService;
import com.design.pattern.strategy.factory.StrategyPatternFactory;
import com.design.pattern.template.FormItemConverter;
import com.design.pattern.template.factory.TemplateBeanFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author @追风少年
 * @description controller
 * @date 2022/4/23
 */
@RestController
@RequestMapping("/pattern")
public class PatternController {

    @Resource
    private StrategyPatternFactory strategyPatternFactory;

    @Resource
    private ModelService modelService;

    @Resource
    private TemplateBeanFactory templateBeanFactory;

    @Resource
    private UserService userService;

    private final Map<String, FormItemConverter> formItemConverterMap = new HashMap<>();

    @Autowired
    private void registerConverter(List<FormItemConverter> converters){
        if (converters == null || CollectionUtils.isEmpty(converters)) {
            return;
        }
        converters.forEach(index -> {
            formItemConverterMap.put(index.getType(), index);
        });
    }

    /**
     * 管道模式实践
     * @return
     */
    @RequestMapping("/pipeline")
    public String pipel(){

        modelService.buildModelInstance();

        return "pipeline success";
    }

    /**
     * 策略模式实践
     */
    @RequestMapping("/strategy")
    public String testStrategy() {
        List<String> actionList = Arrays.asList("insert", "alert");

        actionList.stream().forEach(actionName -> {
            StrategyPatternService strategyService = strategyPatternFactory.getStrategyService(actionName);
            if (strategyService != null) {
                strategyService.doAction();
            }
        });

        return "strategy success";
    }

    /**
     * 模板模式实践
     */
    @RequestMapping("/template")
    public String template() {
        FormItemConverter converter = formItemConverterMap.get("FUZZY_SEARCH");

        converter.convert(null);

        return "template success";
    }

    /**
     * 观察者模式
     * @return
     */
    @RequestMapping("/observer")
    public String observer() {
        userService.register("追风少年");
        return "observer run...";
    }

}
